const Router = require('koa-router');
const upload = require('../utils/upload');
const  uploadImg  = require('../utils/uploadImg');
const fs = require('fs');
const path = require('path')
const showdown = require('showdown')
const converter = new showdown.Converter();

let router = new Router();

router.get('/', async ctx => {
    let pathStr = path.resolve(__dirname,'../note');
    let fileList = fs.readdirSync(pathStr)

    let list = []

    fileList.forEach(file => {
        let fileStr = path.join(pathStr, file);
        let statObj = fs.statSync(fileStr)

        list.push({
            fileName: file.substring(0, file.lastIndexOf('.')),
            atime: statObj.atime.get()['date'],
            mtime: statObj.mtime.format(),
            week: statObj.mtime.get()['week']
        })
    })


    ctx.render('home.html', { list })

    //   ctx.body= fs.readFileSync('./index.html','utf-8')
})

router.get('/note', async ctx=>{
    let file = ctx.query.file;
    if(!file.trim()) return;

    let pathStr = path.resolve(__dirname,'../note',`${file}.md`);
    try {
        let data = fs.readFileSync(pathStr, 'utf-8')
        let html = converter.makeHtml(data)
        ctx.render('content.html', { title: '笔记', html })
    } catch (error) {
        ctx.body = '路径错误，或者笔记不存在哦'

    }
})


router.get('/user', async ctx =>{
    ctx.render('login.html',{});
})


router.post('/api/login',async ctx =>{
    let pwd = ctx.request.body.pwd;

    if(pwd==='4433'){
        ctx.render('user.html',{})
    }
    else{
        ctx.body={err:-200,msg:'登入失败'}
    }
})

router.post('/upload',upload.single('maeizje'),  async (ctx,next) => {

    if (ctx.req.file) {
        
        ctx.body = {succss:true,msg:'上传成功'};
    } else {
        ctx.body ={err:-199,msg:'上传失败'} ;
    }
});

router.post('/uploadImg',uploadImg.single('maeizje'),  async ctx => {
    if (ctx.req.file) {
        
        ctx.body = {succss:true,msg:'上传成功'};
    } else {
        ctx.body ={err:-199,msg:'上传失败'} ;
    }
});

module.exports= router;